package com.ai.nsa.utils.hbase;

import com.ai.nsa.security.HwKerberos;
import com.ai.nsa.utils.pool.ConnectionFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Connection;

/**
 * @author Feng Chen 2017/6/7.
 */
public class HBaseFactory implements ConnectionFactory<Connection> {

    private final Configuration configuration;

    public HBaseFactory(Configuration configuration) {
        this.configuration = configuration;
    }

    public HBaseFactory() {
        this.configuration = HBaseConfiguration.create();
    }

    @Override
    public Connection createConnection() throws Exception {

        // 鉴权
        HwKerberos.auth(configuration);
        return org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(configuration);
    }

    @Override
    public PooledObject<Connection> makeObject() throws Exception {
        return new DefaultPooledObject<Connection>(createConnection());
    }

    @Override
    public void destroyObject(PooledObject<Connection> pooledObject) throws Exception {
        Connection connection = pooledObject.getObject();
        if (connection != null) {
            connection.close();
        }
    }

    @Override
    public boolean validateObject(PooledObject<Connection> pooledObject) {
        Connection connection = pooledObject.getObject();

        if (connection != null) {
            return (!connection.isAborted() && !connection.isClosed());
        }

        return false;
    }

    @Override
    public void activateObject(PooledObject<Connection> pooledObject) throws Exception {

    }

    @Override
    public void passivateObject(PooledObject<Connection> pooledObject) throws Exception {

    }
}
